package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WmNewsMapper wmNewsMapper;

    @Autowired
    WmUserMapper wmUserMapper;

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1.校验参数，分页查询，登录用户
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户需要登录！");
        }
        //2.执行查询
        //封装分页查询条件
        Page<WmNews> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //封装参数查询条件
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        //  如果文章有标题，执行模糊查询
        String keyword = dto.getKeyword();
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(WmNews::getTitle, keyword);
        }
        //  如果有频道id，执行eq查询
        Integer channelId = dto.getChannelId();
        if (channelId != null) {
            wrapper.eq(WmNews::getChannelId, channelId);
        }
        //  如果有文章状态，eq查询
        Short status = dto.getStatus();
        if (status != null) {
            wrapper.eq(WmNews::getStatus, status);
        }
        //  如果开始时间，结束时间不为空按照时间区间查询
        Date beginPubDate = dto.getBeginPubDate();//开始时间
        Date endPubDate = dto.getEndPubDate();//结束时间
        if (beginPubDate != null && endPubDate != null) {
            //按照时间区间查询:区间用between
            wrapper.between(WmNews::getPublishTime, beginPubDate, endPubDate);
        }
        //  参照登录id，eq查询
        wrapper.eq(WmNews::getUserId, user.getId());
        //  按照创建时间降序
        wrapper.orderByDesc(WmNews::getPublishTime);
        //3.执行查询得到结果
        IPage<WmNews> pageResult = page(pageReq, wrapper);
        //4.封装返回结果，设置host字段=》webSite
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), pageResult.getRecords());
        result.setHost(webSite);
        return result;
    }

    /**
     * 自媒体文章发布
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        //1.将dto封装为WmNews对象
        WmNews wmNews = getWmNews(dto);
        //2.保存或修改文章
        saveOrUpdateWmNews(wmNews);
        //如果当前为草稿，则不需要保存关联关系
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(dto.getStatus())) {
            return ResponseResult.okResult();
        }
        //3.保存文章和素材关联关系
        // 3.1  从文章内容中抽取所有的素材路径
        List<String> materialUrls = parseContentImages(wmNews.getContent());
        // 3.2  保存文章内容所引用的素材关联关系
        if (!CollectionUtils.isEmpty(materialUrls)) {
            saveRelativeInfo(materialUrls, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // 3.3  保存文章到封面所引用的素材关联关系(当type=-1的时候代表自动生成封面)
        saveRelativeInfoForCover(dto, materialUrls, wmNews);
        // 发消息，自动审核文章信息
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送文章自动审核消息，当前待审核的文章id==>{}", wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 根据id查询文章的方法
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    /**
     * 根据文章ID删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteNews(Integer id) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    /**
     * 文章上下架操作
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));
        if (WemediaConstants.WM_NEWS_UP.equals(enable)) {
            //发送上架消息
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功发送文章上架的消息，  消息内容：{}", wmNews.getArticleId());
        } else {
            //发送下架消息
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功发送文章下架的消息，  消息内容：{}", wmNews.getArticleId());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage() - 1) * dto.getSize());

        if (StringUtils.isNotBlank(dto.getTitle())) {
            //  concat(%,?,%)
            dto.setTitle("%" + dto.getTitle() + "%");
        }
        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);
        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        if (wmUser != null) {
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     *
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        //人工审核通过
        if (WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)) {
            //4.通知定时发布文章
            //4.1计算时间
            long publishTime = wmNews.getPublishTime().getTime();
            long nowTime = System.currentTimeMillis();
            long remainTime = publishTime - nowTime;
            //4.2发送消息，设置延迟时间
            rabbitTemplate.convertAndSend(
                    PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                    PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                    wmNews.getId(),
                    new MessagePostProcessor() {
                        /**
                         * 消息的后置处理器，可以对消息属性进行设置
                         * @param message
                         * @return
                         * @throws AmqpException
                         */
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            //设置x-delay 延迟时间
                            message.getMessageProperties().setHeader("x-delay", remainTime <= 0 ? 0 : remainTime);
                            return message;
                        }
                    }
            );
            log.info("成功发送延时发布文章消息   文章id:{}  延迟时间:{}", wmNews.getId(), remainTime);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面和素材的关联关系
     * 如果type=-1，需要根据内容素材生成封面列表
     *
     * @param dto
     * @param materialUrls
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> materialUrls, WmNews wmNews) {
        //前端传过来的封面列表
        List<String> images = dto.getImages();
        //如果dto.getType==-1 需要自动生成封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int size = materialUrls == null ? 0 : materialUrls.size();
            if (size > 0 && size <= 2) {
                //单图
                images = materialUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (size > 2) {
                //多图
                images = materialUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            wmNews.setImages(imagesToStr(images));
            this.updateById(wmNews);
        }
        //保存封面和素材的关联关系
        if (!CollectionUtils.isEmpty(images)) {
            //前端传过来的路径（images）是带前缀的路径，需要再替换一次
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     * 保存关联关系的方法
     *
     * @param materialUrls
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materialUrls, Integer newsId, Short type) {
        //1.根据素材路径列表和当前登录用户id 查询素材id集合
        List<Integer> materialIds = wmMaterialMapper.selectRelationsIds(materialUrls, WmThreadLocalUtils.getUser().getId());
        /*List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, materialUrls)
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                .select(WmMaterial::getId)
        );*/
        //2.判断传入路径的数量和素材id的素材是否一致，如果不一致说明素材确实（传过来三个素材，只有两个id）
        if (materialUrls.size() != materialIds.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材缺失，保存失败！");
        }
        //3.将素材id和文章id的引用类型插入到关联表中
        wmNewsMaterialMapper.saveRelations(materialIds, newsId, type);
        /*for (WmMaterial wmMaterial : wmMaterials) {
            //批量保存关联关系
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }*/
        //每次循环都会与数据库进行联系，浪费资源，改用xml的foreach进行批量插入
    }

    /**
     * 抽取文章内容中，所有的素材路径
     * 去除前缀
     * 去除重复
     * 返回路径集合
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //获取流
        mapList.stream()
                //过滤操作
                .filter(m -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(m.get("type")))
                //获取map中的value的值       值==>素材url的完整路径
                .map(m -> String.valueOf(m.get("value")))
                //继续用map将路径中多余的前缀替换掉    用“ ”（空字符）替换
                .map(url -> url.replaceAll(webSite, ""))
                //去除重复的素材    distinct()
                .distinct()
                //收集到集合里边
                .collect(Collectors.toList());
        return null;
    }

    /**
     * 保存和更新文章的方法
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {

        if (wmNews.getId() == null) {
            //如果有文章id就修改
            this.save(wmNews);
        } else {
            //如果没有有文章id就保存
            //删除文章和素材的关联关系表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            this.updateById(wmNews);
        }


    }

    /**
     * 获取文章
     *
     * @param dto
     * @return
     */
    private WmNews getWmNews(WmNewsDTO dto) {
        //  参数校验（content，title，是否登录）
        if (StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章标题或内容不能为空！");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户需要登录！");
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        wmNews.setImages(imagesToStr(dto.getImages()));
        //设置登录用户id
        wmNews.setUserId(user.getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);//默认上架状态
        return wmNews;
    }

    /**
     * 将封面集合转为字符串
     *
     * @param images
     * @return
     */
    private String imagesToStr(List<String> images) {
        if (CollectionUtils.isEmpty(images)) {
            return null;
        }
        return images.stream()
                .map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.joining(","));
    }
}
